package com.hulman.oms.util;

import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

public class DocUtil
{
    public static void export(InputStream templateInputStream, OutputStream outputStream, Map<String, Object> placeholders) throws IOException
    {
        XWPFDocument document = new XWPFDocument(templateInputStream);
        // 替换占位符
        for (XWPFParagraph paragraph : document.getParagraphs())
        {
            for (XWPFRun run : paragraph.getRuns())
            {
                String text = run.getText(0);
                if (text != null)
                {
                    for (Map.Entry<String, Object> entry : placeholders.entrySet())
                    {
                        text = text.replace("{" + entry.getKey() + "}", entry.getValue() == null ? "" : entry.getValue().toString());
                    }
                    run.setText(text, 0);
                }
            }
        }
        document.write(outputStream);
    }
}
